/**
* Class to manage files I/O steams
*
* Project: idbcrown
* Author:  TM
* Date:    22/12/2012
*
* History
* ------------------
* 22/12/2012 - TM - Initial version.
*/

package Util; 

import java.util.*;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import Application.*;

public class libFileUtil
{
   /** Cosntants */
   public static String WIN_EXECUTE_API = "rundll32 SHELL32.DLL,ShellExec_RunDLL ";
   
   /** Reads a given path file and return its content in an array of bytes */
   public static byte[] readBytesFromFile(String filePath) 
    {        
        byte[] bytes = null;
        try
        {
          InputStream inputStream = new FileInputStream(filePath);           
          File file               = new File(filePath);
          long length             = file.length();
                      
          bytes = new byte[(int)length];
      
          // Read in the bytes
          int offset = 0;
          int numRead = 0;
          while (offset < bytes.length         
                        && (numRead=inputStream.read(bytes, offset, bytes.length-offset)) >= 0)                            
                     offset += numRead;          
          inputStream.close(); 
                   
        }
        catch(Exception e)
        {
           libFileDebug.getInstance().write(e);
        }
        return bytes;
    }
    
   /** Reads a given path file and return its content in a String var */    
   public static String[] readFileAsArrayString(File filePath)   
   {
        BufferedReader reader = null;
        File           file   = null;        
        String         line   = null;     
        Vector         resVec = new Vector();
        String[]       result = null;   
        try
        {
          reader              = new BufferedReader(new FileReader(filePath));
          try
          {
            while((line = reader.readLine()) != null)
            {
                resVec.addElement(line);
            }          
          }
          finally
          {
             reader.close();
          }
        }
        catch (IOException e)
        {
           libFileDebug.getInstance().write(e);
        }        
        
        int numLines = resVec.size();
        if (numLines > 0)
        {
           result = new String[numLines];
           for (int i = 0; i < numLines; i++)
             result[i] = (String)resVec.elementAt(i);
        }
        return result;
    }

   /** Reads a given path file and return its content in a String var */    
   public static String readFileAsString(String filePath)   
    {
        StringBuffer fileData = null;
        BufferedReader reader = null;
        File file             = null;        
        try
        {
          file                = new File(filePath);        
          fileData            = new StringBuffer((int)file.length());          
          reader              = new BufferedReader(new FileReader(filePath));
          char[] buf          = new char[1024];
          int numRead=0;
          while((numRead=reader.read(buf)) != -1)
          {
              fileData.append(buf, 0, numRead);
          }          
          reader.close();
        }
        catch (IOException e)
        {
           libFileDebug.getInstance().write(e);
        }        
        return fileData.toString();
    }
    
    /** Write a given String in the path setted in fileName var */    
    public static void writeFileFromString(String data,String fileName)   
    {
      File f=new File(fileName);
      try
      {
         FileOutputStream fop=new FileOutputStream(f);
         if(f.exists())
         {      
           fop.write(data.getBytes());
           fop.flush();
           fop.close();
         }
      }
      catch(Exception e)
      {
         libFileDebug.getInstance().write(e);
      }
    }
    
    /** Says if file exists */    
    public static boolean existsFile(String fileName)   
    {
      boolean result = false;
      File    f      = new File(fileName);
      
      try                { result = f.exists(); }
      catch(Exception e) { }
      
      return result;
    }
    
    /** Tries to delete a file if it exists */    
    public static boolean deleteFile(String fileName)   
    {
      boolean result = false;
      File    f      = new File(fileName);
      
      try                
      { 
         if (f.exists())
           result = f.delete();
         
      }
      catch(Exception e) { }
      
      return result;
    }

    /** Write a given String Array in the path setted in fileName var */    
    public static void writeFileFromStringArray(String[] data,String fileName)   
    {      
      File f=new File(fileName);
      try
      {         
         FileOutputStream fop = new FileOutputStream(f);
         if (data==null)
           return;
           for (int i=0; i<data.length; i++)
           {             
             if(f.exists()&data[i]!=null)
             {                              
                 String line = data[i] + '\n';
                 fop.write(line.getBytes());
                 fop.flush();                          
             }
             else
               System.out.println ("LW.Util.LWFileUtil.java.writeFileFromString:" 
                                 + "the file pretended to write doesn't exist");
           }
           fop.close();
      }                  
      catch(Exception e)
      {
         libFileDebug.getInstance().write(e);
      }
    } 
    
    /** Copy files between destinations */
    public static void copyFiles(String sourceFile, String targetFile) throws IOException
    {
       Path source = Paths.get(sourceFile);
       Path target = Paths.get(targetFile);
       
       Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
    }
    
    /** Write a given byte Array in the path setted in fileName var */    
    public static void writeFileFromByteArray(byte[] data,String fileName)   
    {      
      File f = new File(fileName);
      
      if (data == null)
        return;
       
      try
      {         
         if (!f.exists())
           f.createNewFile();
         
         FileOutputStream fop = new FileOutputStream(f);
         fop.write(data);
         fop.flush();                          
         fop.close();
      }                  
      catch(Exception e)
      {
         libFileDebug.getInstance().write(e);
      }
    } 

    
   // Sends to the windows Run API the command OpenFile   
  public static void RunWindowsFile(String file) 
  {
    String executionPath = System.getProperty("user.dir");
    RunWindowsAbsoluteFile(executionPath + "\\" + file);
  }       
  
 // Sends to the windows Run API the command OpenFile   
 public static String RunWindowsAbsoluteFile(String file) 
 {
   String result = null;
   try 
   {            
     Process p = Runtime.getRuntime().exec(WIN_EXECUTE_API+file);
   }
   catch (Exception e) 
   {
     result = e.getMessage();
     libFileDebug.getInstance().write(e);
   }
   
   return result;
 }       

  
  // Sends to the windows Run API the command OpenFile   
 public static void RunWindowsFile(File file) 
 {
   String filepath = "";
   try 
   {            
     filepath  = file.getAbsolutePath();
     Process p = Runtime.getRuntime().exec(WIN_EXECUTE_API+filepath);
   }
   catch (Exception e) 
   {
     libFileDebug.getInstance().write(e);
   }
 }     
 
 /** Creates a temporary file with the specified content and execute it */  
 public static void createAndExecuteFileContent(String content, String extension) throws IOException 
 {
   File       file = File.createTempFile("export", extension);
   FileWriter out  = new FileWriter     (file);

   out.write(content);
   out.close();
   
   libFileDebug.getInstance().write("Export performed to "+file.getAbsoluteFile());
   RunWindowsFile(file);   
 }
  
}    
    